package com.learn.security.modules.wx.mp.controller;

import cn.hutool.core.util.StrUtil;
import com.learn.security.modules.wx.mp.config.WxMpProperties;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

/**
 * @author lee
 */
@Slf4j
@Controller
@RequestMapping("/wx/oauth2")
public class WxOauth2LoginController {
    private static final String scope = "snsapi_base";
    private static final String defaultRedirectUrl = "springboot-security-learn/wx/redirect/greet";

    @Value("${server.domain}")
    private String domain;

    @Autowired
    private WxMpService wxService;
    @Autowired
    private WxMpProperties properties;

    /**
     * 微信登录
     * @param action
     * @param myRedirectUrl
     * @return
     */
    @GetMapping("/login")
    private ModelAndView login(String action, String myRedirectUrl) {
        String appId = properties.getConfigs().get(0).getAppId();
        if (!this.wxService.switchover(appId)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appId));
        }

        String redirectUrl = domain + defaultRedirectUrl;
        if (StrUtil.isNotBlank(myRedirectUrl)) {
            redirectUrl += "?myRedirectUrl=" + myRedirectUrl;
        }
        String state = "login";
        if ("loginOut".equalsIgnoreCase(action)) {
            state = action;
        }
        String url = wxService.getOAuth2Service().buildAuthorizationUrl(redirectUrl, scope, state);
        log.info("微信登录跳转url:{}", url);
        return new ModelAndView(new RedirectView(url));
    }

}
